package com.shell.scheduler;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.scheduler.job.po.SchdJob;
import com.shell.scheduler.trace.po.SchdTrace;
import com.shell.scheduler.trace.service.SchdTraceService;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.beans.factory.annotation.Autowired;

public class JobTraceListener implements JobListener {
	private Log logger = LogFactory.getLog(getClass());
	@Autowired
	private SchdTraceService schdTraceService;

	public String getName() {
		return "jobTraceListener";
	}

	public void jobToBeExecuted(JobExecutionContext context) {
		this.logger.debug("JobTraceListener.jobToBeExecuted");
	}

	public void jobExecutionVetoed(JobExecutionContext context) {
		this.logger.debug("JobTraceListener.jobExecutionVetoed");
	}

	public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
		this.logger.debug("JobTraceListener.jobWasExecuted");
		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		SchdJob job = (SchdJob) jobDataMap.get("SCHE_JOB");
		Map<String, String> params = (Map) jobDataMap.get("JOB_PARAMS");
		String jobCode = job.getJobCode();
		String message = "";
		if (jobException != null) {
			message = jobException.toString();
		}
		saveTrace(jobCode, params, message);
	}

	private void saveTrace(String jobCode, Map<String, String> params, String message) {
		SchdTrace trace = getJobTrace(jobCode, params, message);
		this.schdTraceService.save(trace);
	}

	SchdTrace getJobTrace(String jobCode, Map<String, String> params, String message) {
		SchdTrace trace = new SchdTrace();
		String traceId = "";
		if ((params != null) && (!params.isEmpty())) {
			traceId = (String) params.get("traceId");
		}
		if (StringUtil.emptyAndNull(traceId)) {
			traceId = SystemUtil.getUUID();
		}
		trace.setTraceId(traceId);
		trace.setJobCode(jobCode);
		trace.setWorkDate(getWorkDate(params));
		trace.setJobTime(DateUtil.getSystemDateTime());

		String success = "1";
		if (!StringUtil.emptyAndNull(message)) {
			message = message.trim();
			if (message.length() > 1000) {
				message = message.substring(0, 1000);
			}
			success = "0";
			trace.setFailureMessage(message);
		}
		trace.setSuccess(success);
		return trace;
	}

	private String getWorkDate(Map<String, String> params) {
		String workDate = "";
		if ((params != null) && (!params.isEmpty())) {
			workDate = (String) params.get("workDate");
		}
		if (StringUtil.emptyAndNull(workDate)) {
			workDate = DateUtil.getSystemDate();
		}
		return workDate;
	}
}
